<template>
	<el-drawer v-model="visible" :title="!dataForm.id ? '新增' : '修改'">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="100px" @keyup.enter="submitHandle()">
			<el-form-item label="单位代码" prop="code">
				<el-input v-model="dataForm.code" placeholder="计量单位代码"></el-input>
			</el-form-item>
			<el-form-item label="单位名称" prop="name">
				<el-input v-model="dataForm.name" placeholder="计量单位名称"></el-input>
			</el-form-item>
			<el-form-item label="单位大类" prop="unitGroup">
				<fast-select v-model="dataForm.unitGroup" dict-type="unit_group" placeholder="单位大类"></fast-select>
			</el-form-item>
			<el-form-item label="描述" prop="description">
				<el-input v-model="dataForm.description" placeholder="描述"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="submitHandle()">确定</el-button>
		</template>
	</el-drawer>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus/es'
import { useErpApi, useErpSubmitApi } from '@/api/erp/unit'

const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()

const dataForm = reactive({
	id: '',
	name: '',
	code: '',
	unitGroup: '',
	description: ''
})

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''

	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}
	//id存在则为修改
	if (id) {
		getErp(id)
	}
}

const getErp = (id: number) => {
	useErpApi(id).then(res => {
		Object.assign(dataForm, res.data)
	})
}

const dataRules = ref({
	name: [
		{ required: true, message: '请输入计量单位名称', trigger: 'blur' },
		{ min: 1, max: 100, message: '长度介于1到100之间', trigger: 'blur' }
	],
	code: { required: true, message: '请输入计量单位代码', trigger: 'blur' },
	unitGroup: { required: true, message: '请选择计量单位大类', trigger: 'blur' }
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate((valid: boolean) => {
		if (!valid) {
			return false
		}

		useErpSubmitApi(dataForm).then(() => {
			ElMessage.success({
				message: '操作成功',
				duration: 500,
				onClose: () => {
					visible.value = false
					emit('refreshDataList')
				}
			})
		})
	})
}

defineExpose({
	init
})
</script>
